<?php
class Macys_Api_V2_Abstract {

	CONST JSON = "application/json";
	CONST XML = "application/xml";

	protected $instance;
	protected $_client;
	protected $log;


	protected $allowedParams = array();
	protected $getparams = array();
	protected $postparams = array();
	protected $rawinput = "";
	protected $currentParams = array();
	protected $contentType = null;
	protected $acceptType = self::JSON;

	protected $conf;
	protected $uri;
	protected $api_key;
	protected $cust_key;
	protected $site;

	protected $_data;

	protected $keyName = null;
	// Will be added as per request
	protected $currentUri = null;
	protected $endPoint = null;

	/**
	 * Method for current request
	 * e.g. GET, POST, DELETE, PUT
	 * @var string
	 */
	protected $method= null;


	final public function __construct($config=null) {
		$this->log = Zend_Registry::get('log');
		$this->_client = new Macys_Base_HttpClient();
		$this->conf = Macys_Base_Config::getInstance();
		$this->getSite();
		$this->setup();
		$this->init();
		$this->setConfig();
	}

	/**
	 * We cannot use until php version 5.3.0
	 public function getInstance() {
		if (!isset(self::$instance)){
		$c = __CLASS__;
		self::$instance = get_called_class();
		}
		return $instance;
		}
		*/


	/**
	 * Sets up the HTTP client to access the services
	 * SetUri Will not be called until required
	 * @param array $config
	 */
	protected function setConfig($config=null) {
		if(isset($this->keyName))
		$conf = $this->conf->getServiceConfig($this->keyName);
		else
		throw new Macys_Base_Exception('Service keyName is not setup properly, Make sure you have servicename matching that to Config file');
		if(isset($config['api_uri'])) {
			$this->uri = $config['api_uri'];
		}
		elseif (empty($this->uri)) {
			$this->uri = $conf['api_uri'];
		}
		if(isset($config['api_key'])) {
			$this->api_key = $config['api_key'];
			$this->_client->setClientHeader($this->api_key);
		}
		elseif (empty($this->api_key)) {
			if(isset($conf[Macys_Constants::MACYS_CLIENT_HEADER])) {
				$this->api_key = $conf[Macys_Constants::MACYS_CLIENT_HEADER];
				$this->_client->setClientHeader($this->api_key);
			}
		}
		if(isset($config['cust_key'])) {
			$this->cust_key = $config['cust_key'];
			$this->_client->setCustomerHeader($this->cust_key);
		}
		elseif (empty($this->cust_key)) {
			if(isset($conf[Macys_Constants::MACYS_CUSTOMER_HEADER])) {
				$this->cust_key = $conf[Macys_Constants::MACYS_CUSTOMER_HEADER];
				$this->_client->setCustomerHeader($this->cust_key);
			}

		}
	}


	public function run() {
		$this->beforeRequest();
		$this->prepareUri();

		if(!empty($this->currentUri))
		$this->_client->setUri($this->currentUri);
		else
		throw new Macys_Api_V2_Exception("Service URI needs to set before calling service you can use prepareURI function in derived classes");
		$this->setRawInput();
		// Set content type
		// This is required to set only after RawInput
		if(isset($this->contentType))
		$this->_client->setContentType($this->contentType);
		// Set Accept Type
		if(isset($this->acceptType))
		$this->_client->setAcceptType($this->acceptType);

		$this->setPostParams();
		$this->setGetParams();


		if(!empty($this->method))
		$this->_client->request($this->method);
		else
		throw new Macys_Api_V2_Exception("Request method Not set, Please Set Request Method in init Function");

		$this->_data = $this->_client->getResponseBodyArray();

		$this->afterRequest();
		return $this;
	}

	protected function setup() {}
	protected function init() {}
	protected function beforeRequest() {}

	private function setPostParams() {
		if(is_array($this->postparams)) {
			if(count($this->postparams) > 0) {
				foreach ($this->postparams as $key => $value) {
					$this->_client->setParameterPost($key,$value);
				}
			}
		}
	}

	private function setGetParams() {
		if(is_array($this->getparams)) {
			if(count($this->getparams) > 0) {
				foreach ($this->getparams as $key => $value) {
					$this->_client->setParameterGet($key,$value);
				}
			}
		}
	}

	private function setRawInput() {
		if(!empty($this->rawinput)) {
			$this->_client->setRawData($this->rawinput);
		}
	}

	protected function afterRequest() {}

	/**
	 * Process the Inputs for Framework Post/Get
	 * Removes unwanted Params of Zend Framework
	 * @param array $params
	 */
	public function processInputParams($params) {
		if(isset($params['submit']))
		unset($params['submit']);
		foreach ($params as $a=>$b) {
			if($b == "" || $b == null)
			unset($params[$a]);
		}

		foreach ($params as $c=>$d) {
			$this->log->debug("Input params : " . $c);
			if(in_array($c, array('controller', "action", "module")))
			unset($params[$c]);
		}
		// Passes on control to Actual Class to process the cleaned params
		$this->processAdditionalInputParams($params);
	}

	/**
	 * Process the Inputs from Controller Post / Get Params
	 * Actual Values that required to be processed by Calls will be processed
	 * @param Array $params
	 */
	protected function processAdditionalInputParams($params) {}


	protected function prepareUri() {
		$this->currentUri = $this->uri . $this->endPoint;
	}

	public function getRawData() {
		return $this->_data;
	}


	//Get Site type now
	protected function getSite() {
		$this->site  = Macys_Base_Config::getInstance()->getSite();
		return $this->site;
	}


}